package com.learn.reflect.itcast.demo3;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * 练习：通过反射实现如下操作
 * Student s = new Student();
 * s.name = "林青霞";
 * s.age = 30;
 * s.address = "西安";
 * System.out.println(s);
 */
public class ReflectDemo02 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        //获取Class对象
        Class<?> clazz=Class.forName("com.learn.reflect.itcast.demo1.Student");

        //Student s = new Student();
        Constructor<?> con = clazz.getConstructor();
        Object obj=con.newInstance();
        //s.name = "林青霞";
        //Field nameField=clazz.getField("name");  //java.lang.NoSuchFieldException: name
        Field nameField=clazz.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(obj,"林青霞");
        System.out.println(obj);

        //s.age = 30;
        Field ageField=clazz.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(obj,30);
        System.out.println(obj);

        //s.address = "西安";
        Field addressField=clazz.getDeclaredField("address");
        addressField.setAccessible(true);
        addressField.set(obj,"杭州");
        System.out.println(obj);

    }
}
